/**
 * 
 */
package org.rrest.core.filesystem.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.rrest.core.filesystem.FileSystemManager;
import org.rrest.file.FileInfo;

public class FileSystemManagerImpl implements FileSystemManager {

	private static final Logger LOGGER = LogManager
			.getLogger(FileSystemManagerImpl.class.getName());

	private static final String WORKING_PATH = "/tmp/distribuida/";

	public FileSystemManagerImpl() {
		super();
		File f = new File(WORKING_PATH);
		if (!f.exists()) {
			LOGGER.info(String.format("Creating directory: %s", WORKING_PATH));
			f.mkdirs();
		}
	}

	public FileInfo getFile(String name) {
		LOGGER.info("RMI : GetFile Called");
		FileInfo result = null;
		File f = new File(WORKING_PATH, name);
		if (f.exists()) {
			try {
				result = new FileInfo(f.getAbsolutePath(),
						FileUtils.readFileToByteArray(f));
			} catch (IOException e) {
				LOGGER.error(String.format("Error reading file %s", name), e);
			}
		}
		return result;
	}

	public boolean addFile(FileInfo file) {
		LOGGER.info("RMI : AddFile Called");
		File f = new File(WORKING_PATH, file.getName());
		try {
			FileUtils.writeByteArrayToFile(f, file.getContent());
		} catch (IOException e) {
			LOGGER.error(
					String.format("Error writing file %s", file.getName()), e);
			return false;
		}
		return true;

	}

	public boolean deleteFile(String name) {
		LOGGER.info("RMI : DeleteFile Called");
		File f = new File(WORKING_PATH, name);
		if (f.exists()) {
			f.delete();
			return true;
		}
		return false;
	}

	public List<String> listFiles(String path) {
		LOGGER.info("RMI : ListFiles Called");
		List<String> res = new ArrayList<String>();
		File f = new File(WORKING_PATH, path);
		File[] files = f.listFiles();
		if (files != null) {
			for (File fi : files) {
				res.add(fi.getName());
			}
		}
		return res;
	}

}
